<template>
  <div>
    <div class="video-box">
      <img
        src="https://ssl-pubpic.51yund.com/1328868323.png"
        class="popup-img"
      />
      <video
        ref="video"
        id="video"
        playsinline
        autoplay
        x5-video-player-type="h5"
        muted
        class="video"
        v-show="videoFlag"
      ></video>
      <canvas id="canvas" width="375" height="500"></canvas>
    </div>
    <canvas id="screenshotCanvas" width="250" height="300"></canvas>
    <img v-show="imageData" :src="imageData" class="face-img" />
    <div class="switch-button">
      <button @click="getFaceImg">采集人像</button>
      <span>{{ positionData.width }}</span>
    </div>
  </div>
</template>

<script>
import tracking from '@/assets/tracking/build/tracking-min.js'
import '@/assets/tracking/build/data/face-min.js'

export default {
  data() {
    return {
      trackerTask: null,
      mediaStreamTrack: null,
      video: null,
      screenshotCanvas: null,
      uploadLock: true, // 上传锁
      faceFlag: false,
      videoFlag: true,
      imageData: '',
      positionData: {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
      },
    }
  },
  mounted() {
    // this.getCamera()
    this.init()
  },
  methods: {
    // 调用打开摄像头功能
    getCamera() {
      this.video = true
      //   兼容性处理
      window.navigator.getUserMedia =
        navigator.getUserMedia ||
        navigator.webKitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      // 正常支持版本
      navigator.mediaDevices
        .getUserMedia({
          // video:{ 'facingMode': "user" },//调用前置摄像头，
          video: { facingMode: { exact: 'environment' } }, //后置摄像头
          audio: false,
        })
        .then((stream) => {
          // 摄像头开启成功
          this.mediaStreamTrack =
            typeof stream.stop === 'function' ? stream : stream.getTracks()[0]
          this.video_stream = stream
          this.$refs.video.srcObject = stream
          this.$refs.video.play()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 初始化设置
    init() {
      this.getCamera()
      this.screenshotCanvas = document.getElementById('screenshotCanvas')
      let canvas = document.getElementById('canvas')
      let context = canvas.getContext('2d')
      // 固定写法
      let tracker = new window.tracking.ObjectTracker('face')
      tracker.setInitialScale(4)
      tracker.setStepSize(2)
      tracker.setEdgesDensity(0.1)

      //摄像头初始化
      this.trackerTask = window.tracking.track('#video', tracker)

      let _this = this
      tracker.on('track', function (event) {
        // 检测出人脸 绘画人脸位置
        context.clearRect(0, 0, canvas.width, canvas.height)
        event.data.forEach(function (rect) {
          //画出边框
          // context.strokeStyle = '#1e1e1e'
          // context.strokeRect(rect.x, rect.y, rect.width, rect.height)
          _this.positionData.x = rect.x
          _this.positionData.y = rect.y
          _this.positionData.width = rect.width
          _this.positionData.height = rect.height
        })
        // event.data.length长度为多少代表检测几张人脸
        if (event.data.length == 1) {
          _this.positionData.x = event.data[0].x
          _this.positionData.y = event.data[0].y
          _this.positionData.width = event.data[0].width
          _this.positionData.height = event.data[0].height
        }
      })
    },

    //开始截图
    getFaceImg() {
      //处理限制     150-180截图出来的最佳
      if (this.positionData.width < 150) {
        this.$toast('请距离再近些，保证人物在识别框内')
      } else if (this.positionData.width > 180) {
        this.$toast('远一点，保证人物在识别框内')
      } else {
        this.isUpload = true
        this.screenshotAndUpload()
      }
    },
    // 上传图片
    screenshotAndUpload() {
      // 上锁避免重复发送请求
      this.uploadLock = false
      // 绘制当前帧图片转换为base64格式
      let canvas = this.screenshotCanvas
      let ctx = canvas.getContext('2d')
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(
        this.$refs.video,
        this.positionData.x,
        this.positionData.y - 20,
        250,
        300,
        0,
        0,
        250,
        300,
      )
      let base64Img = canvas.toDataURL('image/jpeg')
      // 打印出 base64Img
      this.imageData = base64Img

      // 请求接口成功以后打开锁
      // this.uploadLock = true;
    },
    //关闭摄像头
    destroyed() {
      console.log('关闭摄像头')
      this.videoFlag = false
      this.$refs.video.srcObject.getTracks()[0].stop()
    },
  },
}
</script>

<style scoped>
/* 绘图canvas 不需显示隐藏即可 */
#screenshotCanvas {
  display: none;
}

.video-box {
  position: relative;
  width: 100%;
  height: 80vh;
}

.switch-button {
  position: fixed;
  bottom: 20px;
  left: 20px;
  margin-top: 30px;
  margin-left: 30px;
}
video,
canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 150vw;
  /* border: #000000 5px solid; */
}
.popup-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vw;
  z-index: 100;
}

.video {
  width: 100vw;
  height: auto;
}
</style>
